#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort

#需要修改
class api_averagetime_month(abstract_cron) :

    #需要修改
    noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_api_averagetime_day'
    insertTable = 'sdb_statistics_api_averagetime_month'

    def __init__(self) :
        #需要修改
        super(api_averagetime_month,self).__init__(__file__)
        self.lastMonth = dateTypeInterval('last_month')
        self.currentMonth = dateTypeInterval('month')
        self.dateIdent = '%s/%s' % (self.currentMonth[0],self.currentMonth[1])
        self.monthFormat = '%s/%s' % (self.lastMonth[0],self.lastMonth[1])

    def boot(self,timestamp=[]) :
        #self.preBoot()

        sql = self.getSelectSql(timestamp)
        row = self.db.select(sql)

        if row :
            self.writeSql(sql,'succ','select')
            for v in row :
                v['month'] = self.monthFormat
                v['calltime'] = str2sec(self.lastMonth[1],'%Y-%m-%d')-1*24*3600
                if v['sum'] > 0:
                    v['average'] = round(v['alltime'] / v['sum'],2)
                else:
                    v['average'] = 0
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()
        else :
            self.writeSql(sql,'fail','select')
        self.sufBoot()
        print 'ok'

    def getSelectSql(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql = 'SELECT `api`,SUM(`sum`) AS sum,SUM(`alltime`) AS alltime'
        sql += ' FROM ' + self.selectTable
        sql += ' WHERE ' + self.db._filter(timeFilter)
        sql += ' GROUP BY `api`'
        return sql


    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        time_begin = str2sec(self.lastMonth[0],'%Y-%m-%d')
        time_end = str2sec(self.lastMonth[1],'%Y-%m-%d')+1*24*3600
        keyFilter['calltime|between'] = timestamp and timestamp or [time_begin,time_end]
        return keyFilter

    def insertKeys(self) :
        return ['api','sum','alltime','average','calltime','month']


if __name__ == '__main__' :
    obj = api_averagetime_month()
    obj.boot()